package com.project.core.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author mengxj
 * @date 2022/3/3 14:06
 */
@Component
@Slf4j
public class JwtUtil {

    @Value("${jwt.expire}")
    private Long expire;

    @Value("${jwt.secret}")
    private String secret;

    public String generateToken(String loginName) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 60 * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(loginName)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.debug("validate is token error ", e);
            return null;
        }
    }

    public Long getExpire() {
        return expire;
    }
}
